package com.work2.dao;

import com.work2.bean.Users;
import com.work2.utils.DruidManger;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import java.util.ArrayList;
import java.util.List;

public class UsersDaoImpl implements UsersDao {

    //启用连接池
    QueryRunner qr = new QueryRunner(DruidManger.getDataSource());

    @Override
    public int addStu(Users users) throws Exception {
        String sql = " insert into users values (null,?,?) ";
        int i = qr.update(sql,users.getUsername(),users.getUsepwd());
        return i;
    }

    @Override
    public List<Users> findUser() throws Exception {
        String sql = " select * from users ";
        List<Users> list = qr.query(sql, new BeanListHandler<Users>(Users.class));
        return list;
    }

    @Override
    public int delUser(int id) throws Exception {
        String sql = " delete from users where id = ? ";
        int i = qr.update(sql, id);
        return i;
    }

    @Override
    public List<Users> findMove(int id, String username, String usepwd) throws Exception{
        String sql = " select * from users where 1=1";
        List<Object> prams = new ArrayList<>();
        if (id > 0){
            sql += " and id = ? ";
            prams.add(id);
        }
        if(username != null && !username.equals("")){
            sql += " and username = ? ";
            prams.add(username);
        }
        if (usepwd != null && !usepwd.equals("")){
            sql += " and usepwd = ? ";
            prams.add(usepwd);
        }
        List<Users> list = qr.query(sql, new BeanListHandler<Users>(Users.class), prams.toArray());
        return list;

    }

    @Override
    public int uptUser(Users users, int id) throws Exception {
        String sql = " update users set usepwd = ?,username = ? where id = ? ";
        int i = qr.update(sql, users.getUsepwd(), users.getUsername(), id);
        return i;
    }
}
